package main

import (
	"../logger"
	"../util"
	"github.com/valyala/fasthttp"
)

type Server struct {
	producer Producer
}

func (srv *Server) Handle(ctx *fasthttp.RequestCtx) {
	ret := util.NewResult()
	// parse args
	args := parseArgs(ctx)
	// handle request
	if ctx.IsPost() {
		if err := srv.post(args); err != nil {
			ret.WithCode(4001).WithError(err)
		} else {
			ret.WithCode(0)
		}
	}
	// response
	if ret.GetCode() == 0 {
		msg := "Response success to %s, "
		msg = msg + "TABLENAME = %s, data = %s\n"
		logger.Printf(msg, args.ip, args.table, args.data)
		ctx.Success("application/json", ret.PostFinish().Bytes())
	} else {
		msg := "Response error to %s, "
		msg = msg + "TABLENAME = %s, data = %s, "
		msg = msg + "error reason: %v\n"
		logger.Errorf(msg, args.ip, args.table, args.data, ret.GetError())
		ctx.Error(ret.PostFinish().String(), ret.GetCode())
	}
}

type Args struct {
	ip      string
	table   string
	method  string
	path    string
	staffNo string
	data    string
}

func parseArgs(ctx *fasthttp.RequestCtx) (args Args) {
	args = Args{path: string(ctx.Path())}
	if ctx.IsPost() {
		args.ip = ctx.RemoteIP().String()
		args.method = string(ctx.PostArgs().Peek("method"))
		args.table = string(ctx.PostArgs().Peek("tablename"))
		args.data = string(ctx.PostArgs().Peek("data"))
		args.staffNo = string(ctx.PostArgs().Peek("staffNo"))
		msg := "Receive POST request from %s. "
		msg = msg + "TABLENAME = %s, data = %s\n"
		logger.Printf(msg, args.ip, args.table, args.data)
	}
	return
}

func (srv *Server) post(args Args) error {
	if args.data != "" && args.table != "" {
		return srv.producer.ProduceMsg(args)
	} else {
		msg := "Request Parameters Error from %v: data/tablename is empty\n"
		logger.Errorf(msg, args.ip)
		return util.RequestArgsErr
	}
}
